package com.smart.translator.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.smart.translator.MainActivity;
import com.smart.translator.R;
import com.smart.translator.util.UserManager;
import com.smart.translator.util.ConfigManager;
import com.smart.translator.util.NetworkUtils;
import com.smart.translator.data.ConfigApiService;
import com.smart.translator.data.ApiResponse;
import com.smart.translator.data.AppConfig;
import java.util.concurrent.CompletableFuture;
import android.content.Context;

/**
 * 启动Activity
 * 用于检查登录状态并决定跳转到登录页面还是主页面
 */
public class SplashActivity extends AppCompatActivity {
    private static final String TAG = "SplashActivity";
    private static final long SPLASH_DELAY = 1000; // 1秒延迟

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        
        // 延迟检查登录状态和获取配置
        new Handler(Looper.getMainLooper()).postDelayed(this::initializeApp, SPLASH_DELAY);
    }

    /**
     * 初始化应用
     */
    private void initializeApp() {
        // 获取配置信息
        fetchAppConfig();
    }

    /**
     * 获取应用配置
     */
    private void fetchAppConfig() {
        // 检查网络连接
        if (!NetworkUtils.isNetworkConnected(this)) {
            Log.w(TAG, "网络未连接，跳过配置获取");
            checkLoginStatus();
            return;
        }

        Log.d(TAG, "开始获取应用配置...");
        
        CompletableFuture<ApiResponse<AppConfig>> configFuture = ConfigApiService.getAppConfig();
        configFuture.thenAcceptAsync(response -> {
            runOnUiThread(() -> {
                if (response.isSuccess()) {
                    // 配置获取成功
                    AppConfig config = response.getData();
                    ConfigManager configManager = ConfigManager.getInstance(this);
                    configManager.saveConfig(config);
                    
                    // 同时保存到app_config SharedPreferences中，供其他类使用
                    try {
                        android.content.SharedPreferences prefs = getSharedPreferences("app_config", Context.MODE_PRIVATE);
                        prefs.edit()
                            .putString("server_url", config.getServerUrl())
                            .putString("asr_provider", config.getAsrProvider())
                            .putString("tts_provider", config.getTtsProvider())
                            .putString("app_version", config.getAppVersion())
                            .putString("cm3_version", config.getCm3Version())
                            .putString("flash_version", config.getFlashVersion())
                            .apply();
                        Log.d(TAG, "配置已同时保存到app_config SharedPreferences");
                    } catch (Exception e) {
                        Log.e(TAG, "保存到app_config SharedPreferences失败", e);
                    }
                    
                    Log.d(TAG, "配置获取成功: TTS=" + config.getTtsProvider() + 
                          ", ASR=" + config.getAsrProvider() + 
                          ", Server=" + config.getServerUrl());
                } else {
                    // 配置获取失败
                    Log.e(TAG, "配置获取失败: " + response.getError());
                }
                
                // 无论配置获取成功与否，都继续检查登录状态
                checkLoginStatus();
            });
        }).exceptionally(throwable -> {
            runOnUiThread(() -> {
                Log.e(TAG, "配置获取异常", throwable);
                // 配置获取异常，继续检查登录状态
                checkLoginStatus();
            });
            return null;
        });
    }

    /**
     * 检查登录状态
     */
    private void checkLoginStatus() {
        UserManager userManager = UserManager.getInstance(this);
        
        if (userManager.isLoggedIn()) {
            Log.d(TAG, "用户已登录，跳转到主界面");
            startMainActivity();
        } else {
            Log.d(TAG, "用户未登录，跳转到登录界面");
            startLoginActivity();
        }
    }

    /**
     * 启动主Activity
     */
    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 启动登录Activity
     */
    private void startLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
} 